#!/bin/bash
# Copyright 2016 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

# Runs run-webkit-tests and attaches a debugger to the single renderer process.

DEFAULT_TARGET_FLAGS=(--jobs=1 --timeout-ms=100000000 --additional-driver-flag=--no-sandbox --additional-driver-flag=--renderer-startup-dialog)

SAW_DISABLE_FEATURES=false
for TARGET_FLAG in "$@"; do
  if [[ "$TARGET_FLAG" == "--additional-driver-flag=--disable-features="* ]]; then
    TARGET_FLAG="$TARGET_FLAG,SpareRendererForSitePerProcess"
    SAW_DISABLE_FEATURES=true
  fi
  TARGET_FLAGS+=("$TARGET_FLAG")
done
if [ $SAW_DISABLE_FEATURES != true ]; then
  DEFAULT_TARGET_FLAGS+=(--additional-driver-flag=--disable-features=SpareRendererForSitePerProcess)
fi
TARGET_FLAGS=(${DEFAULT_TARGET_FLAGS[@]} ${TARGET_FLAGS[@]})

if [ $# -eq 0 ]; then
  echo "usage: $(basename $0) [run_web_tests.py args...] test-path/test-name.html"
  exit 1
fi

OS=$(uname)
SCRIPTS_DIR=$(dirname $0)
if [[ "$OS" == "Darwin" ]]; then
  CONTENT_SHELL="Content Shell.app"
elif [[ "$OS" == "Linux" ]]; then
  CONTENT_SHELL="content_shell"
else
  echo "Support for $OS has not been tested yet."
  exit 1
fi
RENDERER_REGEX="/$CONTENT_SHELL.* --type=renderer .*--renderer-startup-dialog"

if [ -z "$DEBUGGER" ]; then
  if which lldb > /dev/null; then
    DEBUGGER="lldb"
    CONTINUE="continue"
  elif which gdb > /dev/null; then
    DEBUGGER="gdb -q"
    CONTINUE="signal SIGUSR1"
  else
    echo "No debugger found"
    exit 1
  fi
fi

# Kill existing wpt serve scripts which may have hung from previous runs.
pkill -f "wpt serve"

# Kill existing matching renderers before we begin to ensure a clean run.
pkill -f "$RENDERER_REGEX"

# Run with a single child process as this script attaches only to the first renderer.
$SCRIPTS_DIR/run_web_tests.py ${TARGET_FLAGS[@]} &

wait_renderer_pid() {
  for i in {1..200}; do
    sleep 0.2
    RENDERER_PID=$(pgrep -f "$RENDERER_REGEX")
    [ -n "$RENDERER_PID" ] && return
  done
}

wait_renderer_pid
if [ -n "$RENDERER_PID" ]; then
  # print yellow message
  echo -e "\n\033[1;33mDebugging renderer, use '$CONTINUE' to run.\033[0m\n"
  $DEBUGGER -p $RENDERER_PID
else
  echo "Timed out waiting for renderer."
fi
